package com.ltmonitor.web.controller.command;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.entity.TerminalCommand;
import com.ltmonitor.service.JT808Constants;
import com.ltmonitor.util.StringUtil;
import com.ltmonitor.web.util.JsonMessage;
/**
 * 给终端下发提问指令
 * @author admin
 *
 */
@Controller
@RequestMapping("/sendQuestion")
public class SendQuestionAction extends TerminalCommandAction {
	

	@RequestMapping("/view.action")
	public String view(long vehicleId, Model m) {
		m.addAttribute("vehicleId", vehicleId);
		return "/command/sendQuestion";
	}

	/**
	 * 
	 * @param vehicleId
	 * @param question 下发的文本内容
	 * @param rightAnswerId 正确答案id
	 * @param answerList 问题的备选答案列表
	 * @param displayOptions 设置类型 0 1：紧急 1 保留 2 1：终端显示器显示 3 1：终端TTS播读 4 1：广告屏显示 5～7 保留
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/send.action")
	public JsonMessage  execute(int vehicleId, String question,int rightAnswerId,String inserted,String displayOptions) {

		try {
			//Map params = super.getParams();
			JSONArray arry = JSONArray.fromObject(inserted);
			//displayOptions = ""+params.get("displayOptions");
			String[] displayOption = displayOptions.split(",");

			StringBuilder errorMsg = new StringBuilder();
			if (displayOption == null || displayOption.length == 0) {
				errorMsg.append("请选择提问下发类型!");
			}
			if (rightAnswerId == 0) {
				errorMsg.append("请输入正确答案id!");
			}

			int rowNo = 1;
			String answerList="";
			for (int m = 0; m < arry.size(); m++) {
				JSONObject mi = arry.getJSONObject(m);
				String ID = mi.getString("ID");
				String content = mi.getString("content");
				if (isNumeric(ID) == false)
					errorMsg.append("第一列").append("第" + rowNo + "行必须为数字整数, ");
				if (StringUtil.isNullOrEmpty(content))
					errorMsg.append("第二列").append("第" + rowNo + "行不能为空, ");
				answerList += ID + "," + content + ";";
				rowNo++;
			}
			if (errorMsg.length() > 0)
				return json(false, errorMsg.toString());

			TerminalCommand tc = new TerminalCommand();
			tc.setVehicleId(vehicleId);
			tc.setCmdType(JT808Constants.CMD_QUESTION);
			tc.setRemark(""+rightAnswerId);
			tc.setCmdData(question+";"+answerList);
			int[] bitValues = new int[8];
			for (String op : displayOption) {
				int index = Integer.parseInt(op);
				bitValues[index] = 1;
			}
			ArrayUtils.reverse(bitValues);
			String strBit = "";
			for (int bit : bitValues)
				strBit += bit;
			byte bitValue = Byte.valueOf(strBit, 2); // 将位数组转换为字节值
			tc.setCmd("" + bitValue);
			
			SendCommand(tc);

			return json(true, tc.getEntityId());
		} catch (Exception ex) {
			return json(false, ex.getMessage());
		}
	}


}
